package com.chx.three.mama.activities;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.chx.three.mama.R;
import com.chx.three.mama.adapter.BbsCommonAdapter;
import com.chx.three.mama.model.RingBBS;
import com.chx.three.mama.model.RingItem;
import com.chx.three.mama.utils.BitmapHelper;
import com.chx.three.mama.utils.Constants;
import com.chx.three.mama.utils.SPHelper;
import com.chx.three.mama.utils.TimeHelper;
import com.chx.three.mama.view.ActionBarSelectLayout;
import com.chx.three.mama.view.ScrollListView;
import com.chx.three.mama.view.SildingFinishLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.activity_ring_bbs)
public class RingBBSActivity extends Activity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ScrollView>,ActionBarSelectLayout.OnTopTitleSelected {
    @ViewInject(R.id.ring_bbs_sliding_finish)
    SildingFinishLayout finishLayout;
    //回退按钮
    @ViewInject(R.id.ring_bbs_back)
    ImageButton mBack;
    //创建帖子
    @ViewInject(R.id.ring_bbs_create)
    ImageButton mCreate;
    @ViewInject(R.id.ring_bbs_order)
    ActionBarSelectLayout orderSelect;
    //帖子类型
    RingItem ringItem;
    //网络加载队列
    private RequestQueue requestQueue;
    //置顶的帖子
    private List<String> topTitle;
    private List<RingBBS> topBbs;
    private List<RingBBS> commonBbs;
    //暂时不知道有什么用处
    private int order=1;
    @ViewInject(R.id.ring_bbs_content)
    private PullToRefreshScrollView pullToRefresh;
    ImageView bbsIcon;
    TextView bbsTitle;
    TextView bbsNumber;
    TextView bbsReply;
    ScrollListView topList;
    ScrollListView commonList;
    private BbsCommonAdapter commonAdapter;
    private ArrayAdapter<String> topAdapter;
    //是否是上拉刷新
    boolean isPullUp;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                if(pullToRefresh.isRefreshing()){
                    pullToRefresh.onRefreshComplete();
                }
                pullToRefresh.setRefreshingLabel(timeHelper.getRefreshRingBbsTime(), PullToRefreshBase.Mode.PULL_FROM_START);
                pullToRefresh.setRefreshing(true);
                return;
            }
            if(pullToRefresh.isRefreshing()){
                pullToRefresh.onRefreshComplete();
            }
        }
    };
    private TimeHelper timeHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        mBack.setOnClickListener(this);
        mCreate.setOnClickListener(this);
        topBbs=new ArrayList<>();
        topTitle=new ArrayList<>();
        commonBbs=new ArrayList<>();
        finishLayout.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                finish();
            }
        });
        orderSelect.setOnTopTitleSelected(this);
        pullToRefresh.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefresh.setOnRefreshListener(this);
        //设置加载时的动态图片
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.drawable.xlistview_arrow);
        pullToRefresh.setLoadingDrawable(drawable);
        timeHelper = TimeHelper.getInstance();
        //设置加载中的标题

        ScrollView scrollView = pullToRefresh.getRefreshableView();
        View view = LayoutInflater.from(this).inflate(R.layout.layout_ring_bbs_content, null);
        initView(view);
        //添加界面布局，主要是listView
        getRingIemAndSetBaseData();

        scrollView.addView(view);
        handler.sendEmptyMessageDelayed(1,500);
        //创建新页面
        mCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RingBBSActivity.this,CreateBbsActivity.class);
                intent.putExtra(Constants.BundleKey.KEY_BBS_CREATE_QID,ringItem.getId());
                startActivity(intent);
            }
        });
    }
    private void initView(View view){
        topList=(ScrollListView)view.findViewById(R.id.ring_bbs_top_list);
        commonList=(ScrollListView)view.findViewById(R.id.ring_bbs_common_list);
        topAdapter = new ArrayAdapter<>(this, R.layout.item_ring_bbs_top, R.id.ring_bbs_top_title, topTitle);
        topList.setAdapter(topAdapter);
        commonAdapter = new BbsCommonAdapter(this, commonBbs);
        commonList.setAdapter(commonAdapter);
        bbsIcon=(ImageView)view.findViewById(R.id.ring_bbs_icon);
        bbsTitle=(TextView)view.findViewById(R.id.ring_bbs_title);
        bbsNumber=(TextView)view.findViewById(R.id.ring_bbs_number);
        bbsReply=(TextView)view.findViewById(R.id.ring_bbs_reply_num);
    }
    /**
     * 获取intent传递过来的数据
     */
    private void getRingIemAndSetBaseData() {
        Intent intent = getIntent();
        if(intent!=null){
            Serializable serializableExtra = intent.getSerializableExtra(Constants.BundleKey.KEY_RING_TO_BBS);
            if(serializableExtra!=null){
                if(serializableExtra instanceof RingItem){
                    ringItem=(RingItem)serializableExtra;
                }
            }
        }
        if(ringItem==null){
            return;
        }
        if(!TextUtils.isEmpty(ringItem.getName())){
            bbsTitle.setText(ringItem.getName());
        }
        if(!TextUtils.isEmpty(ringItem.getPost_num_string())){
            bbsNumber.setText(ringItem.getPost_num_string());
        }
        if(!TextUtils.isEmpty(ringItem.getReply_num_string())){
            bbsReply.setText(ringItem.getReply_num_string());
        }
        if(!TextUtils.isEmpty(ringItem.getPic())){
            BitmapUtils bitmapUtils = BitmapHelper.getBitmapUtils();
            bitmapUtils.display(bbsIcon,ringItem.getPic());
        }

    }

    /**
     * 获取数据
     */
    private void requestData() {
        if(ringItem==null){
            return;
        }
        requestQueue = Volley.newRequestQueue(this);
        StringBuilder paht=new StringBuilder("http://www.qubaobei.com/ios/api/bbs_list_v3_test.php?");
        paht.append("user_id=");
        paht.append(SPHelper.getUserId());
        paht.append("&cid=6");
        paht.append("&order=");
        paht.append(order);
        paht.append("&qid=");
        paht.append(ringItem.getId());
        if(isPullUp){
            paht.append("&dated=");
            paht.append(commonBbs.get(commonBbs.size()-1).getDated());
        }
        paht.append("&btime=");
        paht.append(TimeHelper.getInstance().getCurrentData());
        JsonObjectRequest request =
                new JsonObjectRequest(
                        paht.toString(),
                        new JSONObject(),
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject object) {
                                JSONArray data = object.optJSONArray("data");
                                List<RingBBS> top=new ArrayList<>();
                                List<RingBBS> common=new ArrayList<>();
                                List<String> title=new ArrayList<>();
                                if(data!=null){
                                    List<RingBBS> totalBbs=JSON.parseArray(data.toString(),RingBBS.class);
                                    for (RingBBS bbs : totalBbs) {
                                        if(bbs.getPost_type()==1){
                                                top.add(bbs);
                                                title.add(bbs.getTitle());
                                        }else{
                                            common.add(bbs);
                                        }
                                    }
                                    if(!isPullUp){
                                        topBbs.clear();
                                        topTitle.clear();
                                        commonBbs.clear();
                                        topBbs.addAll(top);
                                        topTitle.addAll(title);
                                        commonBbs.addAll(common);
                                    }else{
                                        commonBbs.addAll(0,common);
                                    }
                                    isPullUp=false;
                                    topAdapter.notifyDataSetChanged();
                                commonAdapter.notifyDataSetChanged();
                                    handler.sendEmptyMessage(0);
                                    if(order==1){
                                        timeHelper.setRefreshRingBbsTime();
                                    }else{
                                        timeHelper.setRefreshRingReplyTime();
                                    }
                                }
                            }
                        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(RingBBSActivity.this, "未能获取到数据>.<~", Toast.LENGTH_SHORT).show();
                        handler.sendEmptyMessageDelayed(0,500);
                    }
                });
        requestQueue.add(request);

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.push_right_out);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.ring_bbs_back:
                finish();
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullToRefresh.setRefreshingLabel(timeHelper.getRefreshRingReplyTime(), PullToRefreshBase.Mode.PULL_FROM_START);
        requestData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        if(commonBbs.size()==0){
            return;
        }
        pullToRefresh.setRefreshingLabel(timeHelper.getRefreshRingReplyTime(), PullToRefreshBase.Mode.PULL_FROM_START);
        isPullUp=true;
        requestData();
    }

    /**
     * 最新回复
     */
    @Override
    public void onRightTitleClick() {
        if(order==1){
            pullToRefresh.getRefreshableView().smoothScrollTo(0,0);
            if(requestQueue!=null){
                requestQueue.stop();
            }
            order=2;
            if(pullToRefresh.isRefreshing()){
                pullToRefresh.onRefreshComplete();
            }
            pullToRefresh.setRefreshingLabel(timeHelper.getRefreshRingReplyTime(), PullToRefreshBase.Mode.PULL_FROM_START);
            pullToRefresh.setRefreshing(true);
        }
    }

    /**
     * 最新发帖
     */
    @Override
    public void onLeftTitleClick() {
        if(order==2){
            pullToRefresh.getRefreshableView().smoothScrollTo(0,0);
            if(requestQueue!=null){
                requestQueue.stop();
            }
            order=1;
            if(pullToRefresh.isRefreshing()){
                pullToRefresh.onRefreshComplete();
            }
            pullToRefresh.setRefreshingLabel(timeHelper.getRefreshRingBbsTime(), PullToRefreshBase.Mode.PULL_FROM_START);
            pullToRefresh.setRefreshing(true);
        }
    }

    @Override
    public void onCenterTitleClick() {

    }
}
